<?php
//首页
namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Repositories\ShopRepository;
use Illuminate\Http\Request;
use App\Models\ShopDish;
use App\Models\Shop;
use Illuminate\Support\Facades\DB;
use App\Models\ShopDishAttribute;
use Illuminate\Support\Facades\Validator;

class IndexController extends Controller
{
    protected $shopRepository;
    /**
     * @param $shopRepository
     */
    public function __construct(ShopRepository $shopRepository) {
        $this->shopRepository = $shopRepository;
    }
    /**
     * 获取所有商家信息
     * @return all
     */
    //平台首页
    public function index(Request $request){
        if(!$request->lng || !$request->lat){
            return show(20001,'请输入正确经纬度', '');
        }
        if(!$request->page || !$request->num){
            return show(20002,'请输入分页', '');
        }
        /*if(!$request->type){
            return show(20003,'请输入排序类型', '');
        }*/
        return show(200,'成功', $this->shopRepository->Index($request->lng,$request->lat,$request->page,$request->num,$request->type,$request->business_code));

    }

    //平台首页推荐
    public function getRecommend(){

        //return show(200,'成功', $this->shopRepository->getRecommendShop());
         return view('welcome', ['title' => '首页','data'=>$this->shopRepository->getRecommendShop()]);

    }
    public function ShopInfo(Request $request){
        $id = $request->id;
        if (!isset($id)){
            return show(201,'请传递正确的商家编号');
        }
        $res = Shop::where('id',$id)->first(['id','shop_name','note','shop_pic']);
        return show(200,'成功',$res);
    }
    //平台首页推荐 小程序
    public function getProgramRecommend(){

        return show(200,'成功', $this->shopRepository->getRecommendShop());
        //return view('welcome', ['title' => '首页','data'=>$this->shopRepository->getRecommendShop()]);

    }

    //商家首页
    public function ShopIndex(Request $request){

        if($this->shopRepository->getShopIndex($request->id)===false){
            return redirect('/');
        }
//        return show(200,'OK', $this->shopRepository->getShopIndex($request->id));
        return view('web.shops', ['title' => '商家首页','data'=>$this->shopRepository->getShopIndex($request->id)]);
    }

    // 小程序首页
    public function ShopIndexProgram(Request $request){

        if($this->shopRepository->getShopIndexProgram($request->id)===NULL){
            return show(201,'商家不存在错误');
        }
        return show(200,'商家首页数据获取成功',$this->shopRepository->getShopIndexProgram($request->id));
    }

    //预定首页
    public function ReserveShopIndex(Request $request){
        if(!$request->lng || !$request->lat){
            return show(20001,'请输入正确经纬度', '');
        }
        if(!$request->page || !$request->num){
            return show(20002,'请输入分页', '');
        }
        if (!is_numeric($request->page)){
            return show(20002,'请输入分页', '');
        }
        if (!is_numeric($request->num)){
            return show(20002,'请输入分页', '');
        }
        /*if(!$request->type){
            return show(20003,'请输入排序类型', '');
        }*/
        $s = $request->s;
        return show(200,'成功', $this->shopRepository->getReserveShopIndex($request->lng,$request->lat,$request->page,$request->num,$request->type,$request->business_code,$s));
    }


    //外卖首页
    public function TakeShopIndex(Request $request){
        if(!$request->lng || !$request->lat){
            return show(20001,'请输入正确经纬度', '');
        }
        if(!$request->page || !$request->num){
            return show(20002,'请输入分页', '');
        }
        /*if(!$request->type){
            return show(20003,'请输入排序类型', '');
        }*/
        if (!is_numeric($request->page)){
            return show(20002,'请输入分页', '');
        }
        if (!is_numeric($request->num)){
            return show(20002,'请输入分页', '');
        }
        $s = $request->s;
        return show(200,'成功', $this->shopRepository->getTakeShopIndex($request->lng,$request->lat,$request->page,$request->num,$request->type,$request->type_id,$request->business_code,$s));
    }

    //排队首页
    public function ListShopIndex(Request $request){
        if(!$request->lng || !$request->lat){
            return show(20001,'请输入正确经纬度', '');
        }
        if(!$request->page || !$request->num){
            return show(20002,'请输入分页', '');
        }
        /*if(!$request->type){
            return show(20003,'请输入排序类型', '');
        }*/
        if (!is_numeric($request->page)){
            return show(20002,'请输入分页', '');
        }
        if (!is_numeric($request->num)){
            return show(20002,'请输入分页', '');
        }
        $s = $request->s;
        return show(200,'成功', $this->shopRepository->getListShopIndex($request->lng,$request->lat,$request->page,$request->num,$request->type,$request->business_code,$s));
    }

    //为你推荐
    public function recommend(Request $request)
    {
        $data = ShopDish::where('status',1)->orderBy('sales','desc')
            ->with(['shop'=>function($query){
                $query->select('id','shop_name','shop_avatar','note','shop_pic');
            }])->select(['id','dishes_name','description','discount_price','price','sales','shop_id','thumb'])
            ->where('status',1)
            ->paginate($request['limit']);
        foreach ($data as $dt){
            if (strpos($dt->thumb,';')){
                $res = explode(';',$dt->thumb);
                $dt->thumb=$res[0];
            }
        }
        return show(200,'ok', $data);
    }

    //特惠专区
    public function preferential(Request $request)
    {
        $rules = [
            'page'=>'integer',
            'limit'=>'integer'
        ];
        $message = [
            'page.*'=>'参数有误',
            'limit.*'=>'参数有误'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $perpage = 15;
        if (isset($request->limit)){
            $perpage = $request->limit;
        }

        $data = ShopDish::with(['shop'=>function($query){
            $query->select('id','shop_name','shop_avatar','note','shop_pic');
        }])->select(['id','dishes_name','description','discount_price','price','sales','shop_id','thumb'])
            ->where('discount','<',1)
            ->where('status',1)
            ->orderBy('discount','asc')
            ->paginate($perpage);
        foreach ($data as $dt){
            if (strpos($dt->thumb,';')){
                $res = explode(';',$dt->thumb);
                $dt->thumb=$res[0];
            }
        }
        return show(200,'ok', $data);
    }
//    function checkLong(){
//        var longrg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
//        var lng = $("#itemform [id='lng']").val();
//        if(!longrg.test(lng)){
//            return '经度整数部分为0-180,小数部分为0到6位!';
//        }
//        return true;
//    }

// 还是有问题，待解决
    public function preferentialSecond(Request $request)
    {
        $rules = [
            'page'=>'integer',
            'limit'=>'integer',
            'lat'=>'required',
            'lng'=>'required'
        ];
        $message = [
            'page.*'=>'参数有误',
            'limit.*'=>'参数有误',
            'lat'=>'请给出距离',
            'lng'=>'请给出距离'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $perpage = 15;
        $lat = $request->lat;
        $lng = $request->lng;
        if (isset($request->limit)){
            $perpage = $request->limit;
        }
        $res =  Shop::with(['shopdishes'=>function($query){
            $query->where('discount','<',1)->limit(1)->orderBy('discount','asc')->first();
        }])->paginate($perpage);


        foreach ($res as $key=>$rs){

            if ($rs->shopdishes->isEmpty()){
                unset($res[$key]);
            }else{
                if (strpos($rs->shopdishes[0]['thumb'],',')){
                    $thum = explode(',',$rs->shopdishes[0]['thumb']);
                    $rs->shopdishes[0]['thumb']=$thum[0];
                }
            }
            $rs->distance = calcDistance($lat,$lng,$rs->latitude,$rs->longitude);
        }
//        dd($res[2]->shopdishes);
//        foreach ($res->shopdishes as $dt){
//            if (strpos($dt->thumb,',')){
//                $res = explode(',',$dt->thumb);
//                $dt->thumb=$res[0];
//            }
//        }
        return show(200,'ok', $res);
//        $data = ShopDish::with('shop')
//            ->where('discount','<',1)
//            ->orderBy('discount','asc')
//            ->paginate($request['limit']);
//        foreach ($data as $dt){
//            if (strpos($dt->thumb,',')){
//                $res = explode(',',$dt->thumb);
//                $dt->thumb=$res[0];
//            }
//        }
//        return show(200,'ok', $data);
    }
    //返回外卖的分类
    public function typeData()
    {
        $data = DB::table('shop_types')->get(['id','catname','picture']);
        return show(200,'获取分类成功', $data);
    }

    //返回预定的分类
    public function typeReserveData()
    {
        $data = DB::table('shop_types_reserve')->get(['id','catname','picture']);
        return show(200,'获取分类成功', $data);
    }

    //菜式详情
    public function detailDish(Request $request){
        $rules = [
            'id'=>'required|integer|exists:shop_dishes,id',
        ];
        $message = [
            'id.*'=> '菜式不存在',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        try{
            $dish = ShopDish::find($request->id);
            if($dish){
                $dish = $dish->toArray();
            }else{
                return show(202,'暂无该菜式');
            }
            if ($dish['is_attr'] == 1){
                $dish['attribute'] = ShopDishAttribute::where('dish_id',$request->id)->get();
                //处理多规格
                for($y=0;$y<count($dish['attribute']);$y++)
                {
                    $spec=explode(",", $dish['attribute'][$y]['spec']);
                    foreach($spec as $k2=>$v2)
                    {
                        $spec[$k2] = explode("|",$v2);
                        $specend[$k2]['spec_name'] = $spec[$k2][0];
                        $specend[$k2]['spec_price'] = $spec[$k2][1];
                    }
                    $dish['attribute'][$y]['spec']=$specend;
                }
            }
        }catch (\Exception $e){
        }
        return show(200,'菜式详情获取成功',$dish);
    }

}
